package ken.app.helper;

import java.io.InputStream;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuffXfermode;
import android.graphics.Bitmap.Config;
import android.graphics.PorterDuff.Mode;
import android.graphics.Shader.TileMode;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;

public class Helper {
	
	public static final String folroevveer = "K&C";
	
	/*瀏覽器開啟連結*/
	public static void browerOpenUrl(Activity activity , String url){
		Uri uri = Uri.parse(url);
		Intent intent = new Intent(Intent.ACTION_VIEW, uri);
		activity.startActivity(intent); 
	}

	public static Bitmap readBitMap(Context context, int resId) {
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inPreferredConfig = Bitmap.Config.ALPHA_8;
		opt.inPurgeable = true;
		opt.inInputShareable = true;
		opt.inJustDecodeBounds = true;
		try {
			BitmapFactory.Options.class.getField("inNativeAlloc").setBoolean(opt,true);
		} catch (IllegalArgumentException e1) {
			e1.printStackTrace();
		} catch (SecurityException e1) {
			e1.printStackTrace();
		} catch (IllegalAccessException e1) {
			e1.printStackTrace();
		} catch (NoSuchFieldException e1) {
			e1.printStackTrace();
		}
		// 获取资源图片
		InputStream is = context.getResources().openRawResource(resId);
		BitmapFactory.decodeStream(is, null, opt);
		opt.inJustDecodeBounds = false; 
//		opt.inSampleSize = 2;
		return BitmapFactory.decodeStream(is, null, opt);
	}
	
	public static Bitmap readBitMapforBG(Context context, int resId) {
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inPreferredConfig = Bitmap.Config.ALPHA_8;
		opt.inPurgeable = true;
		opt.inInputShareable = true;
		opt.inJustDecodeBounds = true;
		try {
			BitmapFactory.Options.class.getField("inNativeAlloc").setBoolean(opt,true);
		} catch (IllegalArgumentException e1) {
			e1.printStackTrace();
		} catch (SecurityException e1) {
			e1.printStackTrace();
		} catch (IllegalAccessException e1) {
			e1.printStackTrace();
		} catch (NoSuchFieldException e1) {
			e1.printStackTrace();
		}
		// 获取资源图片
		InputStream is = context.getResources().openRawResource(resId);
		BitmapFactory.decodeStream(is, null, opt);
		opt.inJustDecodeBounds = false; 
		opt.inSampleSize = 2; 
		return BitmapFactory.decodeStream(is, null, opt);
	}
	
	public static Bitmap getLocalBitmap(Context con, int resourceId){
	    InputStream inputStream = con.getResources().openRawResource(resourceId);
	    return BitmapFactory.decodeStream(inputStream, null, getBitmapOptions(1));
	}
	
	public static BitmapFactory.Options getBitmapOptions(int scale){
	    BitmapFactory.Options options = new BitmapFactory.Options();
//	    options.inPurgeable = true;
//	    options.inInputShareable = true;
	    options.inPreferredConfig = Bitmap.Config.RGB_565;
//	    options.inSampleSize = scale;
	    return options;
	}

	public static void ToFullScreen(Activity a) {
		a.requestWindowFeature(Window.FEATURE_NO_TITLE);
		a.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);

	}

	public static View GetLayout(Activity a, int res) {
		/*
		 * LinearLayout layout = (LinearLayout) Helper.GetLayout(this,
		 * R.layout.main); TextView txtHello = new TextView(this);
		 * txtHello.setText("���"); layout.addView(txtHello);
		 * 
		 * setContentView(layout);
		 */

		// LayoutInflater inflate =
		// (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		LayoutInflater inflate = a.getLayoutInflater();

		return inflate.inflate(res, null);
	}
	
	/*字串轉ResourcesID*/
	public static int getResId( Context context ,String defType ,String variableName) {
		try {
			return context.getResources().getIdentifier(variableName ,defType, context.getPackageName());
		} catch (Exception e) {
			return -1;
		}
		
	}

	public static void ChangeLayout(Activity a) {
		TableLayout layout = new TableLayout(a);
		layout.setLayoutParams(new TableLayout.LayoutParams(4, 5));

		layout.setPadding(1, 1, 1, 1);

		for (int f = 0; f <= 13; f++) {
			TableRow tr = new TableRow(a);
			for (int c = 0; c <= 9; c++) {
				Button b = new Button(a);
				b.setText("" + f + c);
				b.setTextSize(10.0f);
				b.setTextColor(Color.rgb(100, 200, 200));
				// b.setOnClickListener(this);
				tr.addView(b, 30, 30);
			} // for

			layout.addView(tr);
		} // for

		a.setContentView(layout);
	}
	//取得現在時間
	public static String getDateTime(String datetype){
//		SimpleDateFormat sdFormat = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
		SimpleDateFormat sdFormat = new SimpleDateFormat(datetype);
		Date date = new Date();
		String strDate = sdFormat.format(date);
		//System.out.println(strDate);
		return strDate;
		}

	public static void ShowMessage(Activity a, String title, String msg) {
		AlertDialog.Builder dlgAbout = new AlertDialog.Builder(a);
		dlgAbout.setTitle(title);
		dlgAbout.setMessage(msg);
		dlgAbout.setIcon(android.R.drawable.ic_dialog_info);
		dlgAbout.setCancelable(false);
		dlgAbout.setNeutralButton("確定", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub

			}
		});
		dlgAbout.show();
	}

	public static void ShowMessage(Activity a, String title, String msg, int btnamount, String[] btntitle, DialogInterface.OnClickListener clicklistenerLeft, DialogInterface.OnClickListener clicklistenerCenter, DialogInterface.OnClickListener clicklistenerRight) {
		AlertDialog.Builder MyAlertDialog = new AlertDialog.Builder(a);
		if (title != null || title.equals("")) {
			MyAlertDialog.setTitle(title);
		}
		MyAlertDialog.setMessage(msg);
		// 建立按下按鈕
//		DialogInterface.OnClickListener OkClick = null;
//		if (clicklistener1 != null) { OkClick = clicklistener1; }

		switch (btnamount) {
		case 1:
			MyAlertDialog.setNeutralButton(btntitle[0], clicklistenerLeft);
			break;
		case 2:
			MyAlertDialog.setPositiveButton(btntitle[0], clicklistenerLeft);
			MyAlertDialog.setNegativeButton(btntitle[1], clicklistenerRight);
			break;
		case 3:
			MyAlertDialog.setPositiveButton(btntitle[0], clicklistenerLeft);
			MyAlertDialog.setNeutralButton(btntitle[1], clicklistenerCenter);
			MyAlertDialog.setNegativeButton(btntitle[2], clicklistenerRight);
			break;
		}
		MyAlertDialog.show();
	}
	
	/**檢查網路狀態*/
	public static boolean isNetworkAvailable( Context context ) {
		  ConnectivityManager cm = (ConnectivityManager) context
		    .getApplicationContext().getSystemService(
		      Context.CONNECTIVITY_SERVICE);
		  if (cm == null) {
		   return false;
		  } else {
		   NetworkInfo[] infos = cm.getAllNetworkInfo();   
		   if (infos != null) {    
		    for (NetworkInfo networkInfo : infos) {
		     if(networkInfo.getState() == NetworkInfo.State.CONNECTED){
		      return true;
		     }
		    }    
		   }
		  }
		  return false;
		 }

	public static int getRandom(int start, int end) {
		return (int) (Math.random() * (end - start + 1)) + start;
	}

	public static Bitmap createReflectionBitmap(Bitmap src) {
		int margin = 0;
		int width = src.getWidth();
		int height = src.getHeight();

		Matrix matrix = new Matrix();
		matrix.preScale(1, -1);

		Bitmap reflection;
		reflection = Bitmap.createBitmap(src, 0, height / 2, width, height / 2,
				matrix, true);

		Bitmap result;
		result = Bitmap.createBitmap(width, height + height / 3,
				Config.ARGB_8888);
		Canvas canvas;
		canvas = new Canvas(result);

		canvas.drawBitmap(src, 0, 0, null);

		canvas.drawBitmap(reflection, 0, height + margin, null);

		Paint paint = new Paint();

		LinearGradient shader;

		shader = new LinearGradient(0, height, 0, result.getHeight() + margin,
				0x90ffffff, 0x00ffffff, TileMode.CLAMP);

		paint.setShader(shader);

		paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));

		canvas.drawRect(0, height, width, result.getHeight(), paint);

		return result;
	}

	public static int getScreenWidth(Activity a) {
		DisplayMetrics dm = new DisplayMetrics();
		a.getWindowManager().getDefaultDisplay().getMetrics(dm);

		return dm.widthPixels;
	}

	public static int getScreenHeight(Activity a) {
		DisplayMetrics dm = new DisplayMetrics();
		a.getWindowManager().getDefaultDisplay().getMetrics(dm);

		return dm.heightPixels;
	}
	
    public static int dip2px(Activity a, float dpValue) {  
        final float scale = a.getResources().getDisplayMetrics().density;  
        return (int) (dpValue * scale + 0.5f);  
    }  
   
    public static int px2dip(Activity a, float pxValue) {  
        final float scale = a.getResources().getDisplayMetrics().density;  
        return (int) (pxValue / scale + 0.5f);  
    }	
	
	// Returns the index of the first occurrence of the lower or upper specified character a-z
	public static int getFirstAlphaIndex(String toFind){
		int idx = -1;		
	
		for (int i = 0 ; i < toFind.length() ; i++){
			if (Character.UnicodeBlock.of(toFind.charAt(i)) == Character.UnicodeBlock.BASIC_LATIN) {
				idx = i;
				break;
			}
		}
		
		return idx;
	}
	
	public static String insertString(String origin, int pos, String insert){
		try {
			return (origin = origin.substring(0, pos) + insert + origin.substring(pos));
		} catch (Exception e) {
			return origin;
		}
	}
	
	public static String timestampToDate(long timestamp , String yyyyMMDD){
		// 設定時間格式&時區
		SimpleDateFormat format = new SimpleDateFormat(yyyyMMDD);
//		format.setTimeZone(TimeZone.getTimeZone("GMT+08:00"));
//		long b=1335297780;
//		Long d=Long.parseLong(b)*1000;
		Timestamp ts = new Timestamp(timestamp*1000);
		return format.format(ts);
	}
	
	//關閉輸入法鍵盤
	public static void keybordOff (Context context){
		
		try {
			InputMethodManager inputMethodManager = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
//			inputMethodManager.showSoftInput(v,InputMethodManager.SHOW_FORCED);
			boolean isOpen=inputMethodManager.isActive();
			if (isOpen) {
				inputMethodManager.hideSoftInputFromWindow(((Activity) context).getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}

	}
	
}
